<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8" />
    <meta name="Cache-Control" content="private">
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="minimum-scale=1, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="css/mui.min.css">
    <title>立减优惠活动</title>
    <script src="js/flexphone.js"></script>
    <!--<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>-->
</head>

<body>
<div id="app" class="mask-btn">
    <div class="contenner">
        <img class="main_img" src="images/box_img.png" alt="">
        <div class="term">
            <img src="images/time_s.png" alt="">
            <p class="term">有效期: 5月16日~5月19日</p>
        </div>
        
        <div class="btn_contenner">
            <img src="images/file_2.png" alt="">
            <div class="btn_box">
                <img class="btn_img" src="images/receive.png" alt="">
            </div>
            <div class="explain">
                已领取的优惠券可以在“<span class="channel"></span>”查看
            </div>
        </div>
        
        <div>
            <img src="images/text_box.png" alt="">
        </div>
    </div>

    <div class="prompt">
        <p>1.本次活动仅限广东、江苏、福建、湖北的用户可参与;</p>
        <p>2.活动时间为2017年5月16日~5月19日;</p>
        <p>3.参与本次活动优惠的不可以与其他优惠同享;</p>
        <p>4.公司车和警告单不参与该次活动优惠;</p>
        <p>5.本次活动车行易具有最终解释权。</p>
        <p style="font-size: 0.28rem; color: red;"><span>PS:</span>因用户强烈要求，本活动延时一天至5月19日。</p>
    </div>
    <div class="btn_s">
        立即前往办理
    </div>
    <!--领取成功-->
    <div class="mask_success">
        <img src="images/Fill.png" alt="">
        <p>领取成功</p>
    </div>

    <!--领取失败-->
    <div class="mask_fail">
        <img src="images/Path.png" alt="">
        <p>领取失败请重试</p>
    </div>

</div>

<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/mui.min.js"></script>
<script src="js/cx580.jsApi.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="js/WeiXinAPI.js"></script>
<script src="https://tongji.cx580.com/userBehavior/static/js/cxytongji_v3.0.js"></script>
<!--<script src="//cx580.oss-cn-shenzhen.aliyuncs.com/cweb/js/react-dom-15.min.js"></script>-->
<script type="text/javascript">
	$(document).ready(function(){
        if(getChannelOfBrowser()=='aliPay'){
            AlipayJSBridge.call('hideOptionMenu');  ///隐藏支付宝右按钮
        }else if(getChannelOfBrowser()=='app'){
        	$('.channel').text('我的 - 优惠券');
	        $('.btn_s').hide();
        }else {
	        $('.channel').text('个人中心 - 我的优惠券');
        }
        var production = window.location.href.indexOf('https://webservice.cx580.com/') > -1 ? true : false; //是否为生产环境

        /**
         * 切换生产或测试环境
         * "http://192.168.1.165:9071/"; //测试
         * "https://192.168.1.54:8023/im/"; //测试环境暂时不部署https 否则会提示网络错误
         * "https://webservice.cx580.com/";//生产
         */
        //var baseApiUrl = production ? "https://webservice.cx580.com/coupon/getCoupon/" : location.hostname=="localhost"?"http://192.168.1.165:9071/":"http://"+location.host+"/";//  192.168.2.225
        $('.btn_s').on('click',function(){
        	var authType='';
	        switch (getChannelOfBrowser()){
		        case 'aliPay':
		        	authType = 'aliPay';
                    break;
		        case 'weixin':
			       authType = 'weixin';
			        break;
		        case 'qq':
			       authType = 'qq';
			        break;
	        }

	        window.cxytj.recordUserBehavior({
		        eventId: 'lijianyouhui_banli',
		        eventType: '2', //事件类型
		        attr1: '立即前往办理按钮',
		        eventTime: '',  //触发时间
	        });

	        setTimeout(function(){
                window.location.href='https://banli.cx580.com/CarInfo/QueryList.aspx?userType='+authType;
            },50)

        })
        var baseApiUrl = production ? "https://webservice.cx580.com/" : "http://192.168.1.165:9071/";
			if(getChannelOfBrowser() == 'aliPay'|| getChannelOfBrowser() == 'weixin'||getChannelOfBrowser() == 'qq'){
                _singleSignOn(function test(){
                    $('.btn_img').on('click',function(){
                        SelectAdvertisementGet(sessionStorage.getItem("userId"),sessionStorage.getItem("token"))
                    })
                })
			}else {
				var userInfo = getUserIdAndToken();
				setTimeout(function(){
					userInfo = getUserIdAndToken();
					SelectAdvertisement(userInfo.userId,userInfo.token,userInfo.version,userInfo.deviceId);
                    //getUser(userInfo.userId,userInfo.deviceId)
					$(".btn_img").on('click',function () {
						userInfo = getUserIdAndToken()

                        window.cxytj.recordUserBehavior({
                            eventId: 'lijianyouhui_lingqu',
                            eventType: '2', //事件类型
                            attr1: '领取优惠券按钮',
                            eventTime: '',  //触发时间
                        });

						if (!userInfo.userId || !userInfo.token) {
							var btnArray = ['否', '是'];
							mui.confirm('你还没有登录，是否登录？', '', btnArray, function(e) {
								if (e.index == 1) {
									setTimeout(function (){
										_appLogin(function () {
											userInfo = getUserIdAndToken();
											SelectAdvertisement(userInfo.userId,userInfo.token,userInfo.version,userInfo.deviceId);
										}); //先登录
									},100)

								} else {

								}
							})
						}else {
							SelectAdvertisementGet(userInfo.userId,userInfo.token,userInfo.version);
						}
					});

				},150)
			}

			//单点登录
        function _singleSignOn(callBack) {
	            callBack()
				var loginType=_getTypeByChannel();
				var search = '?' + window.location.href.split('?')[1];
				//判断是否为首页
				var pattern = /\S+index.html[^(\/)]*([#|%23])?(\/)?$/;
				var isHome = pattern.test(window.location.href);
				//判断是否已经登录过，路由内部判断
				var isLogined = sessionStorage.getItem('loginStatus') == 'true';
                /* alert(window.location.href);
                 alert(isHome);
                 alert(isLogined);*/
				if (isHome && !isLogined && (typeof(search) == "undefined" || search.indexOf("userId=") === -1)) {
					//首页检测不到登录信息，跳单点登录

					//清除所有前端缓存
					localStorage.removeItem("userId");
					localStorage.removeItem("token");
					localStorage.removeItem("userType");
					localStorage.removeItem("openId");
					//不存在userId
					if (sessionStorage.getItem("closeWebview")) {
						sessionStorage.setItem("closeWebview", "");
						if (navigator.userAgent.indexOf("AlipayClient") !== -1) {
							AlipayJSBridge.call('closeWebview'); //支付宝 关闭view
						}
					} else {
//						if (window.location.host.indexOf("localhost") !== -1 || window.location.href.indexOf("test") > 0) {
//													alert('test4')
//							//本地PC调试
//						} else {
							if (navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1) {
								sessionStorage.setItem("closeWebview", 1); //安卓系统下次访问的时候直接退出 不再去请求单点登录
							}
                        /* var homeUrl = window.location.protocol + '//' + window.location.host + '/dist/index.html'; //回调地址
                         if(window.location.host.indexOf("192.168") !== -1){
                         //本地手机端调试
                         homeUrl = window.location.protocol + '//' + window.location.host + '/index.html'; //回调地址
                         }*/
							var homeUrl = window.location.href;
							var authIstest = window.location.host === 'webservice.cx580.com' ? 'https://auth.cx580.com/' : 'http://testauth.cx580.com/'; //正式||测试 单点登录
							//window.location.replace(`${authIstest}Auth.aspx?authType=${loginType.authType}&userType=${loginType.userType}&clientId=CheWu&redirect_uri=${homeUrl}`);
							window.location.replace(authIstest+'Auth.aspx?authType='+loginType.authType+'&userType='+loginType.userType+'&clientId=CheWu&redirect_uri='+homeUrl)

					}
					return false;
				}

				else if (localStorage.getItem("userId") != null) {
					//非首页，已登录过
	                  //如果本地缓存中存在用户信息则直接复制到session中供代码调用
					sessionStorage.setItem("userId", localStorage.getItem("userId"));
					sessionStorage.setItem("token", localStorage.getItem("token"));
					sessionStorage.setItem("userType", localStorage.getItem("userType"));
					sessionStorage.setItem("openId", localStorage.getItem("openId"));

                    SelectAdvertisement(sessionStorage.getItem("userId"),sessionStorage.getItem("token"))
					return true;
				}
				else {
					//首页登录之后回到页面，执行初始化信息操作
            /*    alert('2'+localStorage.getItem("userId"));*/
					var userId = '';
					userId = /[\?|&]userId=([^&]+)/g;
					userId = userId.exec(search);
					userId = userId ? userId[1] : "";
					sessionStorage.setItem("userId", userId); //保存openId
					var token = '';
					token = /[\?|&]token=([^&]+)/g;
					token = token.exec(search);
					token = token ? token[1] : "";
					sessionStorage.setItem("token", token); //保存token
					var userType = '';
					userType = /[\?|&]userType=([^&]+)/g;
					userType = userType.exec(search);
					userType = userType ? userType[1] : "";
					sessionStorage.setItem("userType", userType); //保存userType
					var openId = '';
					openId = /[\?|&]userOpenId=([^&]+)/g;
					openId = openId.exec(search);
					openId = openId ? openId[1] : "";
					sessionStorage.setItem("openId", openId); //保存userType
					//用户信息缓存本地
					localStorage.setItem("userId", userId);
					localStorage.setItem("token", token);
					localStorage.setItem("userType", userType);
					localStorage.setItem("openId", openId);
					sessionStorage.setItem("loginStatus", "true");

                  /*
                 alert(localStorage.getItem("userId"));
                 alert(localStorage.getItem("token"));
                 alert(localStorage.getItem("userType"));
                 alert('拿到用户信息');
                  */
                SelectAdvertisement(sessionStorage.getItem("userId"),sessionStorage.getItem("token"))
                return true;
            }
        }

			//根据不同渠道获取单点登录参数
			function _getTypeByChannel(){
				var type={};
				switch (getChannelOfBrowser()){
					case 'aliPay':
						type={
							authType:'AliPayCityService',
							userType:'AliPay'
						};
						break;
					case 'weixin':
						type={
							authType:'weixin',
							userType:'weixin'
						};
						break;
					case 'qq':
						type={
							authType:'qq',
							userType:'qq'
						};
						break;
				}
				return type;
			}

			//通过userAgent识别浏览器所在的渠道,仅识别渠道，不识别特定浏览器
			function getChannelOfBrowser(){
				var channel='';
				//支付宝
				if(navigator.userAgent.indexOf("AlipayClient") !== -1) {
					channel='aliPay';
				}
				//app
				else if(navigator.userAgent.indexOf("appname_cxycwz") > -1){
					channel= 'app'
				}
				else if(navigator.userAgent.indexOf("MicroMessenger")>-1){
					channel='weixin';
				}
				else if(navigator.userAgent.indexOf("QQ")>-1){
					channel='qq';
				}
				else{
					channel='unKnown'
				}
				return channel;
			}



        var g_userId ='',
            g_userToken ='',
	        g_deviceId = '',
			g_version='';


        //发送请求修改状态
        function SelectAdvertisementGet(userId,token,version) {
            //alert('刷新点击')

            if($('.btn_img').attr('src')=='images/receiveNo.png'){
                mui.toast('你已经领取过了')
                 return false;
            }

          /*
           * 判断在什么环境使用
           * */
	        if(!version){
		        version=''
	        }

	        window.cxytj.recordUserBehavior({
		        eventId: 'lijianyouhui_lingqu',
		        eventType: '2', //事件类型
		        attr1: '领取优惠券按钮',
		        eventTime: '',  //触发时间
	        });

            $.ajax({
                url: baseApiUrl+'coupon/getCoupon',
                type: "GET",
                data: {
                    userid: userId,   //用户ID
                    usertype: getChannelOfBrowser(),  //用户类型
                    version: version,  //APP版本
                    token: token, //token
                    activity: 'ACT_TIME_LIMIT_DISCOUNT_201705'
                },
                cache: false,
                dataType: "json",
                success: function (res) {
                	//alert(JSON.stringify(res));
                    if(res.code==1000){
                        $('.btn_img').attr('src','images/receiveNo.png');
                        $('.mask_success').fadeIn();
                        setTimeout(function(){
                            $('.mask_success').fadeOut();
                        },1500)
                    }else if(res.code == 4444){
                        $('.mask_fail').fadeIn();
                        setTimeout(function(){
                            $('.mask_fail').fadeOut();
                        },1500)
                    }
                },
                error: function(xhr, type){
                    console.error(xhr, type)
                }
				});
			}

		function getUser(userId,device) {
            getUserIdAndToken();
            window.cxytj.init({ //以下为初始化示例，可新增或删减字段
                productId: 'lijianyouhui', //产品ID
                productVersion: '1.0', //产品版本
                productUserId: device,//APP端 （设备标记ID）
                channel: getChannelOfBrowser(), //推广渠道
                isProduction: true, //生产环境or测试环境 默认测试环境
                userId: userId, //用户ID
                sessionId: '', //会话ID
                ip: '', //IP地址
                longitude: '', //经度
                latitude: '' //纬度
            }); //初始化通用数据 isProduction为true时表示生产环境，默认为测试环境
        }


			///请求数据 领取状态
        function SelectAdvertisement(userId,token,version,device) {
        	getUser(userId,device);

        	if(!version){
        		version=''
            }

	        window.cxytj.recordUserBehavior({
		        eventId: 'lijianyouhui_shouye',
		        eventType: '2', //事件类型
		        attr1: '打开立减优惠活动页面',
		        eventTime: '',  //触发时间
	        });

            $.ajax({
					url: baseApiUrl+'coupon/selectCoupon',
					type: "GET",
					data: {
						userid: userId,   //用户ID
						usertype: getChannelOfBrowser(),  //用户类型
						version: version,  //APP版本
						//token: token, //token
                        activity: 'ACT_TIME_LIMIT_DISCOUNT_201705'
					},
					cache: false,
					dataType: "json",
					success: function (res) {
						//(JSON.stringify(res))
						///status	int	是	1是已领取,0是未领取
						if(res.code==1000){
							if(res.data.status == 1){
                                $('.btn_img').attr('src','images/receiveNo.png');
                            }else if(res.data.status == 0){
                                $('.btn_img').attr('src','images/receive.png');
                            }
						}else if(res.code = 4444){ /// 约定也是未领取状态
                           // $('.btn_img').attr('src','images/receive.png');
						}
					},
					error: function(xhr, type){
						//alert.error(xhr, type)
					}
				});
        }


        // 取得某个url参数
        function getUrlParam(name, url) {
            var urlSearch = '?' + window.location.href.split('?')[1];
            var search = url || urlSearch.substr(1);

            if (search != '') {
                var re = new RegExp('(^|&|\\?)' + name + '=([^&]*)($|&)');
                var arr = search.match(re);
                if (arr !== null) {
                    return decodeURI(arr[2]);
                }
            }
            return '';
        }

			/**
         * 从 app 中获取用户 token
         */
        function _getUserInfoFromApp() {
            try {
            window.cx580.jsApi.call({
                    "commandId": "",
                    "command": "getSymbol",
                    "data": {
	                    "accountId": "",
                        "token": "",
	                    "version": "",
	                    "type|orderNum": "",
                        "userid":"",
                    }
                }, function(data){
            	g_deviceId = data.data.userid;
                g_userId = data.data.accountId;
                g_userToken = data.data.token;
                g_version = data.data.version;
            });
            } catch (error) {
                //执行到这里，说明不在 app 中运行
                // alert("调试信息：调用APP JS SDK出错了 获取APP信息出错了");
            }
        }

        /**
         * app 登陆
         */
        function _appLogin(callback) {
            window.cx580.jsApi.call({
                "commandId": "",
                "command": "login"
            }, function (data){
                localStorage.setItem("upLoginState", "1"); //用户登录状态发生变化
            if (data.data.accountId) {
                g_userId = data.data.accountId;
                _getUserInfoFromApp();
                if (callback) {
                    callback();
                }
            } else {
                //登录失败
                //   common.closeAppView(); //关闭APP视图
            }
        });
        }

        /**
         * 检测是否为车行易app
         */
        function isCXYApp() {
            var isCXYApp = navigator.userAgent.indexOf('appname_cxycwz') > -1 ? true : false;
            return isCXYApp;
        }

        /**
         * 获取 userId 和 token
         */
        function getUserIdAndToken() {
            if (isCXYApp()) {
                _getUserInfoFromApp();
            }
            return {
                userId: g_userId,
                token: g_userToken,
	            version: g_version,
	            deviceId:g_deviceId,
            }
        }

    });
</script>
</body>

</html>
